package cz.andsolutiondroid.services;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import cz.andsolutiondroid.activity.RealityMainActivity;
import cz.andsolutiondroid.model.Reality;
import cz.andsolutiondroid.model.RealityDataSource;

public class RealitySynchronize{
	
	private static final String URL = "http://www.zapabike.cz/reality/index.php?presenter=RealitySynchronize";
	
	public RealitySynchronize() {
		
	}
	
	public HashMap upload(List<Reality> r){
		
		HttpClient client = new DefaultHttpClient();
		
		try {
			HttpPost p = new HttpPost(URL);

			JSONObject json = new JSONObject();
			JSONArray data = new JSONArray();

			for (Reality reality : r) {
				data.put(reality.toJsonString());
			}
			
			json.put("data", data);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);   
		    nameValuePairs.add(new BasicNameValuePair("data", json.toString()));
		    
		    p.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			//URLEncoder.encode(query, "utf-8")
		    
			HttpResponse resp = client.execute(p);
			
			BufferedReader br = new BufferedReader(
						new InputStreamReader(
								resp.getEntity().getContent(), "utf-8"));
			
			String line;
			String response = "";
			
			while ( (line = br.readLine()) != null ) {
				
				response += line;
			}		
			
			response = response.replaceAll("&quot;", "'");
			
			JSONObject res = new JSONObject(response);
			String status = (String) res.get("status").toString();
			String message = (String) res.get("message").toString();

			
			// odpoved serveru
			if(status.contains("[OK]")){
				
				JSONArray hashes = res.getJSONArray("hashes"); 
				Log.d("Response: ", hashes.toString());
				HashMap<String, Object> resp1 = new HashMap<String, Object>();
				
				resp1.put("message", message);
				resp1.put("hashes", hashes);
				
				return resp1;
			}else{
				Log.d("Response: ", status);
				HashMap<String, Object> resp1 = new HashMap<String, Object>();
				
				resp1.put("message", message);
				
				return resp1;
			}
			
		} catch (Exception e) {
			Log.e("SERVER", "Error retrieving data.", e);
		}
		
		return null;
	}
	
	
}
